<template>
  <div class="fdsCleaningRuleset-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="编码" prop="number">
          <el-input
            placeholder="请输入清洗规则编码"
            v-model="searchForm.number"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input
            placeholder="请输入清洗规则名称"
            v-model="searchForm.name"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="状态" prop="enabled">
          <el-input
            placeholder="请输入状态"
            v-model="searchForm.enabled"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button @click="startClear"> 重置 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-pagination-content">
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增清洗规则
        </el-button>
        <!-- <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          设置清洗规则应用范围
        </el-button> -->
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="number" label="子版本总数" width="100" />
          <el-table-column prop="number" label="编码" width="130" />
          <el-table-column prop="name" label="规则名称" width="140" />
          <el-table-column prop="stepCount" label="清洗步骤" width="140">
            <template #default="scope">
              <span style="margin-right: 10px">{{
                scope.row.stepCount || 0
              }}</span>
              <el-button
                size="small"
                type="primary"
                @click="showStepDetail(scope.row)"
                >步骤详情</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="enabled" label="状态" width="80">
            <template #default="scope">
              <div
                class="table-column-item"
                style="display: flex; align-items: center"
              >
                <el-tag type="success" v-if="scope.row.enabled">启用</el-tag>
                <el-tag type="danger" v-else>禁用</el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="170" />
          <el-table-column label="操作" min-width="220px" fixed="right">
            <template #default="scope">
              <!-- v-if="rolePermission.editRolePerm" -->
              <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 2)"
                >编辑</el-button
              >
              <el-button
                v-if="scope.row.enabled"
                type="danger"
                size="small"
                @click.prevent="showEnabledDialog(scope.row)"
                >禁用</el-button
              >
              <el-button
                v-else
                type="success"
                size="small"
                @click.prevent="showEnabledDialog(scope.row)"
                >启用</el-button
              >
              <!-- v-if="rolePermission.removeRolePerm" -->
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <FdsCleaningRulesetAdd v-model="addUpdateRef"></FdsCleaningRulesetAdd>
    <FdsCleaningRulesetRemove v-model="removeRef"></FdsCleaningRulesetRemove>
    <FdsCleaningRulesetEnable v-model="enabledRef"></FdsCleaningRulesetEnable>
    <FsdCleaningRulesetDrawer v-model="stepRef"></FsdCleaningRulesetDrawer>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  getFdsCleaningRulesetPagination,
  getFdsCleaningRulesetAllList,
} from '@/api/fds-cleaning-ruleset.api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// import { useUserPermission } from "@/utils/permission.utils";
import FdsCleaningRulesetRemove from './FdsCleaningRulesetRemove.vue'
import FdsCleaningRulesetAdd from './FdsCleaningRulesetAdd.vue'
import FdsCleaningRulesetEnable from './FdsCleaningRulesetEnable.vue'
import FsdCleaningRulesetDrawer from './FsdCleaningRulesetDrawer.vue'
import { getCanUseCode } from '@/api/fms-code-dict.api'

const titleName = `清洗规则设置表`
const stepRef = reactive({
  visible: false,
  form: {
    id: '',
    enabled: '',
  },
})
const showStepDetail = (item: any) => {
  stepRef.visible = true
  stepRef.form = item
}

const enabledRef = reactive({
  visible: false,
  form: {
    id: '',
    enabled: '',
  },
  refreshDataList: () => {
    getDataList()
  },
})
const showEnabledDialog = (item: any) => {
  enabledRef.visible = true
  enabledRef.form.id = item.id
  enabledRef.form.enabled = item.enabled ? '0' : '1'
}

/****
 * =============== 新增、修改相关操作 =====================
 */
const addUpdateRef = reactive({
  visible: false,
  disabled: false,
  title: `清洗规则`,
  curSelectRow: {},
  roleList: [],
  form: {
    number: '',
    name: '',
    enabledBefore: '',
    needCleanEmpty: '',
    beforeDiscardMaterial: '',
    needBatchClean: '',
    noCleanMaterial: [],
    activeName: '第一步',
    restRuleDetails: [
      {
        title: '第一步',
        step: 1,
        //清洗方式
        cleanWay: '0',
        //选择用水类型
        waterUsageType: '1',

        //清洗时长
        cleanTime: '',
        soakTime: 1,
        intervalTime: 1,
        rinseTime: 1,

        //清洗提示标题
        cleanPromptTitle: '',
        //清洗提示内容
        cleanPromptContent: '',
        //是否需要再次确认
        reconfirm: '',
      },
    ],
  },
  rules: {},
  refreshDataList: () => {
    getDataList()
  },
})

// const requestCanUseCode = () => {
// 	getCanUseCode({ type: 8 })
// 			.then((res: any) => {
// 				console.log('getCanUseCode: ', res)
// 				addUpdateRef.form.number = res
// 			})
// 			.catch((err) => {
// 				ElMessage.error(err.msg)
// 			})
// }

const showAddEditDialog = (item: any, type: number) => {
  //新增
  if (item.target) {
    let form = {
      number: '',
      name: '',
      enabledBefore: '',
      needCleanEmpty: '',
      beforeDiscardMaterial: '',
      needBatchClean: '',
      noCleanMaterial: [],
      activeName: '1',
      restRuleDetails: [
        {
          name: '1',
          title: '第一步',
          step: 1,
          //清洗方式
          cleanWay: '0',
          //选择用水类型
          waterUsageType: '1',
          //清洗时长
          cleanTime: 1,

          soakTime: 1,
          intervalTime: 1,
          rinseTime: 1,

          //清洗提示标题
          cleanPromptTitle: '',
          //清洗提示内容
          cleanPromptContent: '',
          //是否需要再次确认
          reconfirm: '',
        },
      ],
    }
    addUpdateRef.visible = true
    addUpdateRef.disabled = false
    addUpdateRef.form = form
    // requestCanUseCode()
    return
  }

  let form = {
    id: item.id,
    number: item.number,
    name: item.name,
    enabled: item.enabled,
    enabledBefore: item.enabledBefore,
    dayTime: item.dayTime,
    defaultValue: item.defaultValue,
    remark: item.remark,
    restType: item.restType,
    needRemind: item.needRemind,
    stepCount: item.stepCount,
    stepCountInt: item.stepCountInt,
    needBatchClean: item.needBatchClean,
    needCleanEmpty: item.needCleanEmpty,
    beforeDiscardMaterial: item.beforeDiscardMaterial,
    baseline: item.baseline,
    cleanMode: item.cleanMode,
    children: item.children,
    disabled: false,
  }
  addUpdateRef.visible = true
  addUpdateRef.disabled = true
  addUpdateRef.form = form
}

/****
 * =============== 删除操作 =====================
 */
const removeRef = reactive({
  visible: false,
  title: `清洗规则设置表`,
  curSelectRow: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showRemoveDialog = (item: any) => {
  removeRef.visible = true
  removeRef.curSelectRow = item
}

/****
 * =============== 搜索、表格、分页 =====================
 */
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const searchForm = ref({
  number: '',
  name: '',
  enabled: '',
  enabledBefore: '',
  dayTime: '',
  defaultValue: '',
  remark: '',
  restType: '',
  needRemind: '',
  stepCount: '',
  stepCountInt: '',
  needBatchClean: '',
  needCleanEmpty: '',
  beforeDiscardMaterial: '',
  baseline: '',
  cleanMode: '',
  children: '',
})

const tableLoading = ref(false)
const tableData = ref([])
/***
 * 开始搜索
 */
const startSearch = () => {
  formData.pageIndex = 1
  getDataList()
}

/***
 * 清空搜索条件
 */
const startClear = () => {
  formData.pageIndex = 1
  let value = searchForm.value
  Object.keys(value).forEach((key) => {
    ;(value as any)[key] = ''
  })
  getDataList()
}

const handleSizeChange = (value: number) => {
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  formData.pageIndex = value
  getDataList()
}

const getDataList = () => {
  let searchCondition: any = {}

  let number = searchForm.value.number
  if (number) {
    searchCondition.number = number
  }

  let name = searchForm.value.name
  if (name) {
    searchCondition.name = name
  }
  let enabled = searchForm.value.enabled
  if (enabled) {
    searchCondition.enabled = enabled
  }

  tableLoading.value = true
  getFdsCleaningRulesetPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {
      tableLoading.value = false
      console.log(res)

      let list = res.list || []
      for (let i = 0; i < list.length; i++) {
        let item = list[i]
        let children: string = item.children || ''
        if (children && children.length > 0) {
          item.children = JSON.parse(children)
        }
        item.stepCount = item.children.length || 0
      }
      tableData.value = list
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

onMounted(() => {
  getDataList()
})
</script>
<style lang="scss" scoped>
.fdsCleaningRuleset-page {
  height: 100%;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}

.tag-field {
  .el-tag {
    margin-right: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.search-field {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px 20px 0px 20px;
  border-radius: 8px;
}

.fdsCleaningRuleset-page-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
